package com.kim.bookshop.book.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import com.kim.bookshop.book.bean.Book;
import com.kim.bookshop.book.bean.PageBean;
import com.kim.bookshop.book.service.BookService;
import com.kim.bookshop.category.bean.Category;
import com.kim.bookshop.category.service.CategoryService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.commons.CommonUtils;

public class BookAction extends ActionSupport implements ModelDriven<Book> {
	
	private  File file;
	private String fileFileName;
	private String fileContentType;
	private Category category;
	
	private static final long serialVersionUID = 1L;
	private Book book=new Book();
	private String cid;
	private int count;
	
	private HttpServletRequest request;
	private HttpSession session;
	private ServletContext application;
	private ApplicationContext ctx;	
	private BookService bookService;
	private CategoryService categoryService;
	
	public BookAction(){
		request=ServletActionContext.getRequest();
		session=request.getSession();
		application= session.getServletContext();
		ctx=(ApplicationContext) application.getAttribute("ApplicationContext"); 
	    bookService=(BookService) ctx.getBean("bookService");
	    categoryService=(CategoryService) ctx.getBean("categoryService");
	}
	
	public String index(){
		session.setAttribute("popList", bookService.getPopList());
		return "index";
	}
	
	//搜索
	public String search(){
		String bname=request.getParameter("keywords");
		if(bname!=null){
			request.setAttribute("pageBean", bookService.searchBook(bname));
			 
			return SUCCESS;
		}
		return "";
	}
	
	
	/**
	 * 查看库存
	 * @return
	 * @throws Exception
	 */
	public String stock() throws Exception {
		//request.setAttribute("stacks", bookService.findByCategory(cid));
		//获取页码
		int pc=getPc(request);
		int ps=20;
		request.setAttribute("pageBean", bookService.findByCategoryPage(cid, pc, ps));
		request.setAttribute("categoryList", categoryService.findAll());
		return SUCCESS;
	}
	
	/**
	 * 根据bid加载库存
	 * @return
	 * @throws Exception
	 */
	public String loadstock() throws Exception{
		request.setAttribute("stock", bookService.load(book.getBid()));
		return "stockinfo";
	} 
	
	/**
	 * 更新库存
	 * @return
	 * @throws Exception
	 */
	public String updatestock() throws Exception {
		System.out.println(book.getBid());
		System.out.println(book.getStock());
			bookService.updateStock(book.getBid(), book.getStock());
		return  "stocklist";
	}
	
	/**
	 * 清空库存
	 * @return
	 * @throws Exception
	 */
	public String cleanstock() throws Exception{
		System.out.println(book.getBid());
		bookService.cleanStock(book.getBid());
		return "stocklist";
	}
		/**
		 * 查询所有图书信息
		 * 调用bookService的fandAll()方法获取
		 *保存到request
		 */
		public String list() throws Exception {
			
			int pc=getPc(request);
			int ps=20;
			PageBean<Book> pBean=bookService.findAllPage(pc, ps);


			request.setAttribute("pageBean", pBean);
			
//			
//			String contextPath=request.getContextPath();
//			String servletPath=request.getServletPath();
//			String queryString=request.getQueryString();
//			System.out.println(contextPath+servletPath+queryString);
			
			return SUCCESS;
			
//			bookService=(BookService) ctx.getBean("bookService");
//			List<Book> booklist=bookService.findAll();
//			request.setAttribute("booklist", booklist);
//			System.out.println("list after");
			

			
	
		}
		
		//返回下架
		public String offlinelist() throws Exception {
			bookService=(BookService) ctx.getBean("bookService");
			List<Book> booklist=bookService.findOffLine();
			request.setAttribute("booklist", booklist);
			return SUCCESS;
		}
		
		/*
		 *获取页面传递得bid
		 *调用service获取book对象
		 *显示book信息到页面
		 */
		public String info() throws Exception {
				String bid=book.getBid();
				request.setAttribute("categoryList", categoryService.findAll());
				request.setAttribute("book", bookService.load(bid));
				return  "dec";
			}
		
		/**
		 * 新增书籍
		 * @return
		 * @throws Exception
		 */
		public String add() throws Exception {

			category=CommonUtils.toBean(request.getParameterMap(),Category.class);//封装分类
			book.setBid(CommonUtils.uuid());//设置id
			book.setCategory(category);//设置图示分类
			book.setPostdate(new Date());//设置上架时间
			String root=ServletActionContext.getServletContext().getRealPath("/book_img");
			
			InputStream in=new FileInputStream(file);
			OutputStream out=new FileOutputStream(new File(root,fileFileName));
		
			byte[] buffer=new byte[500];
			int leng=0;
			 while(-1 != (leng = in.read(buffer, 0, buffer.length)))
		        {
		            out.write(buffer);
		        }
		        
		        out.close();
		        in.close();
		    book.setDel(false);
		      book.setImage("book_img/"+fileFileName);
		      System.out.println("书籍信息："+book);
			bookService.save(book);
			return "listbook";
		}

		/**
		 * 按分类查询
		 * @return
		 */
		public String byCategory(){
			PageBean<Book> pageBean=new PageBean<Book>();
			pageBean.setBeanList(bookService.findByCategory(cid));
			request.setAttribute("pageBean", pageBean);
			return SUCCESS;
		}
		
		/**
		 * 添加前加载分类
		 * @return
		 */
		public String preadd(){
			request.setAttribute("categoryList", categoryService.findAll());
			return "preadd";
		}
		
		
		//重新上线
		public String reonlime(){
			String bid=request.getParameter("bid");
			bookService.reonline(bid);
			return  "listoffline";
		}
		
		
		
		
		/**
		 * 删除
		 * @return
		 */
		public String del(){
			System.out.println(book.getBid());
			bookService.remove(book.getBid());
			return "listbook";
		}
		
		/**
		 * 修改前加载
		 * @return
		 */
		public String mod(){
			String bid=book.getBid();
			request.setAttribute("categoryList", categoryService.findAll());
			request.setAttribute("book", bookService.load(bid));
			return SUCCESS;
		}
		
		/**
		 * 修改信息
		 * @return
		 */
		public String editmsg(){
	
			category=categoryService.load(cid);
			book.setCategory(category);
			System.out.println(category);
			System.out.println(book);
			bookService.updateInfo(book);
			return "listbook";
		}
		@Override
		public Book getModel() {
			return book;
		}
		public String getCid() {
			return cid;
		}
		public void setCid(String cid) {
			this.cid = cid;
		}
		
		
		//获取当前页码
		public int getPc(HttpServletRequest request){
			String value=request.getParameter("pc");
			if(value==null || value.trim().isEmpty()){
				return 1;
			}
			return Integer.parseInt(value);
		}
		

		
		public Category getCategory() {
			return category;
		}

		public void setCategory(Category category) {
			this.category = category;
		}

		public int getCount() {
			return count;
		}

		public void setCount(int count) {
			this.count = count;
		}

		public File getFile() {
			return file;
		}

		public void setFile(File file) {
			this.file = file;
		}

	
		public String getFileFileName() {
			return fileFileName;
		}

		public void setFileFileName(String fileFileName) {
			this.fileFileName = fileFileName;
		}

		public String getFileContentType() {
			return fileContentType;
		}

		public void setFileContentType(String fileContentType) {
			this.fileContentType = fileContentType;
		}

	
}
